from django.shortcuts import render
from rest_framework.views import APIView
import os
from kdjangos.settings import UPLOAD_ROOT
from rest_framework.response import Response
from PIL import Image,ImageDraw,ImageFont
import cv2
# from models import Goods,Ddan
# Create your views here.


# 文件上传
class UploadFile(APIView):

    def post(self, request):
        # 接收参数
        myfile = request.FILES.get('file')

        # 建立文件流对象
        f = open(os.path.join(UPLOAD_ROOT, '', myfile.name), 'wb')
        # 写入
        for chunk in myfile.chunks():
            f.write(chunk)
        f.close()

        if 'jpg'or 'png'in myfile.name:
            name = myfile.name
            print(name)
            # 打开图片
            img = Image.open("./static/upload/" + name)
            # 生成画笔
            draw = ImageDraw.Draw(img)
            # 设置水印字体大小
            font=ImageFont.truetype("simsun.ttc", 30, encoding="GBK")
            # 修改图片，将水印画到图片上
            draw.text((670, 500), 'django2.0.4', fill=(220,20,60), font=font)
            # 存储图片
            img.save('C:/Users/69540/student/kaoshi/kdjangos/static/upload/' + name)
            # 读图
            img = cv2.imread('C:/Users/69540/student/kaoshi/kdjangos/static/upload/' + name)
            # 执行压缩,压缩比约50%
            cv2.imwrite('./static/upload/ks.png', img, [cv2.IMWRITE_PNG_COMPRESSION,9])

        return Response({'filename': myfile.name})



from myapp.ser import GoodsSer,DdanSer
from myapp.models import Goods,Users,Xqing,Ddan
# from kaoshi.kdjangos.myapp.models import Goods,Users
#商品列表
class GoodsList(APIView):

    def get(self,request):

        uid = request.GET.get('uid')

        #查询订单
        orderslist = Goods.objects.filter(id=int(uid))

        #序列化
        orderslist_ser = GoodsSer(orderslist,many=True)

        return Response(orderslist_ser.data)

class DdanList(APIView):
    def get(self,request):
        uid = request.GET.get('uid')

        # 查询订单
        orderslist = Ddan.objects.filter(id=int(uid)).first()

        # 序列化
        orderslist_ser = DdanSer(orderslist, many=True)

        return Response(orderslist_ser.data)

